<?php
/**
 * (jobs)
 */
namespace App\Jobs\Operation;

use App\Models\Operation\ProfitSku;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
class ProfitSkuUp implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $data;

    /**
     * ProductSkuUp constructor.
     * @param $data
     */
    public function __construct($data)
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     * @return void
     */
    public function handle()
    {
        $this->exeFillData($this->data);
    }

    private function exeFillData($items){
        foreach ($items as $item){
            $profitSku = ProfitSku::query()
                ->where('country_id',$item['country_id'])
                ->where('psku_id',$item['psku_id'])
                ->get();
            foreach ($profitSku as $_ps){
                if(isset($item['fba_fee']) && $item['fba_fee']){
                    $_ps->fba_fee = $item['fba_fee'];
                }
                if(isset($item['commission']) && $item['commission']){
                    $_ps->commission = $item['commission'];
                }
                if(isset($item['sale_price']) && $item['sale_price']){
                    $_ps->sale_price = $item['sale_price'];
                }
                $fbaFeeFlag = $_ps->country_id == 20 ? false : true;
                $_ps->status = ProfitSku::getStatus($_ps->status,$_ps->sale_price,$_ps->fba_fee,$_ps->commission,$fbaFeeFlag);
                $tpl = round($_ps->tpl_rmb / $_ps->rate_odds,3);
                $_ps->cost = ProfitSku::getCost($tpl,$_ps->sale_price,$_ps->head_cost,$_ps->fba_fee,$_ps->commission,$_ps->return,$_ps->vat);
                $_ps->profit = round($_ps->sale_price - $_ps->cost,3);
                $_ps->profit_rate = $_ps->sale_price == 0 ? 0 : round($_ps->profit / $_ps->sale_price,3);
                $_ps->save();
            }
        }
    }
}
